package com.zcx.excel.controller;

import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.zcx.excel.common.util.EasyPoiUtils;
import com.zcx.excel.common.vo.ApiResult;
import com.zcx.excel.pojo.Price;
import com.zcx.excel.pojo.PriceExample;
import com.zcx.excel.service.PriceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author zhaochangxin
 * @Title: Excel导入导出测试
 * @Package com.zcx.exceldemo.controller
 * @Description: Excel导入导出测试
 * @date 2022/3/25 10:42
 */
@RequestMapping("excel")
@RestController
@Api(tags = "Excel测试")
public class ExcelTestController {
    private static final String TO_EXCEL_SUCCESS = "导出成功";

    @Autowired
    PriceService priceService;
    /**
    　* @author zhaochangxin
    　* @Description:查询所有产品并导出Excel
    　* @Param priceExample:
    　* @return: com.zcx.exceldemo.common.vo.ApiResult
    　* @date 2022/3/25 10:53
    　* @throws IOException
    　*/
    @ApiOperation(value = "查询所有产品并导出Excel")
    @GetMapping("/toExcel")
    public ApiResult queryAllPriceListToExcel(PriceExample priceExample, HttpServletResponse response) throws IOException {
        long start = System.currentTimeMillis();
        PriceExample.Criteria criteria=priceExample.createCriteria();
        criteria.andCreatedByIsNotNull();
        List<Price> pricesList = priceService.queryAllPriceList(priceExample);
//        EasyPoiUtil.exportExcel(pricesList,"123","123",Price.class,"1.xls",response);
        EasyPoiUtils.exportExcel(Price.class,pricesList,"D:\\Tesla\\test\\","pricelist.xls");
        long end=System.currentTimeMillis();
        System.out.println("ExcelEasyPoi导出所用时间:" + (end - start));
        return ApiResult.success(TO_EXCEL_SUCCESS);
    }
    /**
    　* @author zhaochangxin
    　* @Description:导入Excel数据
    　* @return: com.zcx.exceldemo.common.vo.ApiResult
    　* @date 2022/3/25 15:44
    　* @throws
    　*/
    @ApiOperation(value = "导入Excel数据")
    @GetMapping("/AddFromExcel")
    public ApiResult AddPriceFromExcel() throws IOException {
        long start = System.currentTimeMillis();
        List<Price> addList=EasyPoiUtils.importExcel(
                new File("src/main/resources/excel/pricelist.xls"),
                Price.class,
                new ImportParams());
        for (Price price : addList) {
            priceService.insertPrice(price);
            System.out.println(price);
        }
        long end=System.currentTimeMillis();
        System.out.println("ExcelEasyPoi导入所用时间:" + (end - start));
        return ApiResult.success(TO_EXCEL_SUCCESS);
    }

}
